package org.cainiao.servlet.workflow;

import io.swagger.v3.oas.annotations.Parameter;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.cainiao.servlet.workflow.service.MyService;
import org.flowable.task.api.Task;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequiredArgsConstructor
public class MyRestController {

    private final MyService myService;

    @GetMapping(value = "/process/{key}")
    public void startProcessInstance(
            @Parameter(description = "流程定义ID", required = true) @PathVariable("key") String key) {
        myService.startProcessByKey(key);
    }

    @PostMapping(value = "/process/v2")
    public void startProcessInstance(@RequestBody StartProcessRepresentation startProcessRepresentation) {
        myService.startProcess(startProcessRepresentation.getAssignee());
    }

    @PostMapping(value = "/process")
    public void startProcessInstance() {
        myService.startProcess();
    }

    @RequestMapping(value = "/tasks", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public List<TaskRepresentation> getTasks(@RequestParam String assignee) {
        List<Task> tasks = myService.getTasks(assignee);
        List<TaskRepresentation> dtos = new ArrayList<>();
        for (Task task : tasks) {
            dtos.add(new TaskRepresentation(task.getId(), task.getName()));
        }
        return dtos;
    }

    @AllArgsConstructor
    @Data
    static class TaskRepresentation {
        private String id;
        private String name;
    }

    @Data
    static class StartProcessRepresentation {
        private String assignee;
    }
}
